package com.da.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.da.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author da
 * @time 2023/12/11 下午 10:31
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    //处理抛出的自定义的异常,返回统一的格式给前端
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result myException(HttpServletRequest request, MyException e) {
        log.error("请求的url : {}, 错误信息 : {}", request.getRequestURL(), e.getMessage());
        return Result.builder()
                .msg(e.getMessage())
                .code(e.getCode())
                .data(e.getMessage()).build();
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result otherException(HttpServletRequest request, Exception e) {
        log.error("请求的url : {}, 错误信息 : {}", request.getRequestURL(), e.getMessage());
        e.printStackTrace();
        if (e instanceof NotLoginException) {
            return Result.error(e.getMessage());
        }
        return Result.error("服务器出现错误");
    }

}
